package com.tuanzi.loan.workflow.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.tuanzi.loan.workflow.entity.FormBinding;
import com.tuanzi.loan.workflow.repository.FormBindingRepository;
import com.tuanzi.loan.workflow.service.FormBindingService;
import com.tuanzi.loan.workflow.service.WorkflowManagerService;

/**
 * @author Ray
 * @date 2018/01/16
 */
@Service
@Transactional
public class FormBindingServiceImpl implements FormBindingService {

	@Autowired
	private FormBindingRepository formBindingRepository;
	@Autowired
	private WorkflowManagerService workflowManagerService;

	@Override
	public FormBinding findByProcDefIdAndActId(String procDefId, String actId) {
		return formBindingRepository.findByProcDefIdAndActId(procDefId, actId);
	}

	// @Autowired
	// private FormBindingRepository formBindingRepository;

	// @Resource
	// private WorkflowManagerService workflowManagerService;
	//
	// @Resource
	// private FormAttributeService formAttributeService;
	//
	@Override
	public List<FormBinding> findAllByProcDefId(String procDefId) {
		return formBindingRepository.findAllByProcDefId(procDefId);
	}

	@Override
	public void deleteByProcDefId(String procDefId) {
		formBindingRepository.deleteInBatch(formBindingRepository.findAllByProcDefId(procDefId));
	}
	//
	// @Override
	// public BaseResponse<String> delById(FormBindingDeleteRequest request) {
	// BaseResponse<String> response = new
	// BaseResponse<>(ErrorResponseEnum.INVOKE_SUCCESS);
	//
	// FormBinding record = new FormBinding();
	// record.setId(request.getFormBindingId());
	//
	// int count = mapper.deleteByPrimaryKey(record);
	// if (count == 1) {
	// response.setResult(new BaseResult<>(true, "删除成功"));
	// } else {
	// response.setResult(new BaseResult<>(false, "删除失败"));
	// }
	//
	// return response;
	// }

	@Override
	public void synchronizeFormBinding(String oldProcDefId, String newProcDefId) {

		List<FormBinding> oldFormBindings = formBindingRepository.findAllByProcDefId(oldProcDefId);
		for (FormBinding oldFormBinding : oldFormBindings) {

			FormBinding newFormBinding = new FormBinding();
			BeanUtils.copyProperties(oldFormBinding, newFormBinding, new String[] { "id" });
			newFormBinding.setProcDefId(newProcDefId);
			formBindingRepository.save(newFormBinding);
		}
	}

	public void delete(List<FormBinding> entities) {
		entities.stream().forEach(this::delete);
	}

	public void delete(FormBinding formBinding) {
		// formAttributeService.deleteByFormBindingId(formBinding.getId());
		// super.delete(formBinding);
	}

	@Override
	public FormBinding saveOrUpdate(FormBinding formBinding) {
		formBinding.setFormUrl(StringUtils.trim(formBinding.getFormUrl()));
		return formBindingRepository.save(formBinding);
	}

}
